'use client';

import { useState } from 'react';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import {
  Calculator,
  TrendingUp,
  DollarSign,
  Clock,
  Users,
  Zap,
  Target,
  BarChart3,
  PieChart,
  ArrowRight,
} from 'lucide-react';

/**
 * ROI计算器输入参数接口
 */
interface ROIInputs {
  currentTransactions: number; // 当前日交易量
  currentLatency: number; // 当前平均延迟(ms)
  currentCost: number; // 当前年度运营成本
  teamSize: number; // 开发团队规模
  projectDuration: number; // 项目周期(月)
}

/**
 * ROI计算结果接口
 */
interface ROIResults {
  performanceImprovement: number; // 性能提升百分比
  costSavings: number; // 年度成本节约
  revenueIncrease: number; // 收入增长
  paybackPeriod: number; // 投资回收期(月)
  totalROI: number; // 总投资回报率
  implementationCost: number; // 实施成本
}

/**
 * 行业基准数据
 */
const industryBenchmarks = {
  banking: {
    name: '银行业',
    performanceGain: 300,
    latencyReduction: 85,
    costReduction: 40,
    icon: '🏦',
  },
  fintech: {
    name: '金融科技',
    performanceGain: 400,
    latencyReduction: 80,
    costReduction: 30,
    icon: '💳',
  },
  securities: {
    name: '证券业',
    performanceGain: 200,
    latencyReduction: 60,
    costReduction: 45,
    icon: '📈',
  },
  insurance: {
    name: '保险业',
    performanceGain: 150,
    latencyReduction: 70,
    costReduction: 35,
    icon: '🛡️',
  },
};

interface ROICalculatorProps {
  className?: string;
}

/**
 * ROI计算器组件
 * 帮助用户评估采用CActor框架的投资回报
 */
export function ROICalculator({ className = '' }: ROICalculatorProps) {
  const [inputs, setInputs] = useState<ROIInputs>({
    currentTransactions: 1000000,
    currentLatency: 100,
    currentCost: 1000000,
    teamSize: 5,
    projectDuration: 6,
  });

  const [selectedIndustry, setSelectedIndustry] =
    useState<keyof typeof industryBenchmarks>('banking');
  const [results, setResults] = useState<ROIResults | null>(null);

  /**
   * 计算ROI结果
   */
  const calculateROI = () => {
    const benchmark = industryBenchmarks[selectedIndustry];

    // 实施成本估算 (基于团队规模和项目周期)
    const implementationCost =
      inputs.teamSize * 50000 * (inputs.projectDuration / 12);

    // 性能提升带来的收入增长
    const performanceImprovement = benchmark.performanceGain;
    const revenueIncrease =
      inputs.currentTransactions * 0.001 * (performanceImprovement / 100) * 365;

    // 成本节约 (基于运营成本降低)
    const costSavings = inputs.currentCost * (benchmark.costReduction / 100);

    // 总收益
    const totalBenefit = revenueIncrease + costSavings;

    // 投资回收期 (月)
    const paybackPeriod = implementationCost / (totalBenefit / 12);

    // 总ROI (3年期)
    const totalROI =
      ((totalBenefit * 3 - implementationCost) / implementationCost) * 100;

    setResults({
      performanceImprovement,
      costSavings,
      revenueIncrease,
      paybackPeriod,
      totalROI,
      implementationCost,
    });
  };

  /**
   * 更新输入值
   */
  const updateInput = (field: keyof ROIInputs, value: number) => {
    setInputs(prev => ({ ...prev, [field]: value }));
  };

  /**
   * 格式化货币显示
   */
  const formatCurrency = (amount: number) => {
    if (amount >= 1000000) {
      return `¥${(amount / 1000000).toFixed(1)}M`;
    } else if (amount >= 1000) {
      return `¥${(amount / 1000).toFixed(0)}K`;
    }
    return `¥${amount.toFixed(0)}`;
  };

  /**
   * 格式化百分比显示
   */
  const formatPercentage = (value: number) => {
    return `${value > 0 ? '+' : ''}${value.toFixed(1)}%`;
  };

  return (
    <div className={`max-w-7xl mx-auto ${className}`}>
      <div className="text-center mb-12">
        <div className="inline-flex items-center px-4 py-2 rounded-full bg-blue-100 text-blue-700 text-sm font-medium mb-6">
          <Calculator className="w-4 h-4 mr-2" />
          ROI计算器
        </div>
        <h2 className="text-3xl md:text-4xl font-bold text-gray-900 mb-4">
          投资回报
          <span className="bg-gradient-to-r from-blue-600 to-cyan-600 bg-clip-text text-transparent">
            计算器
          </span>
        </h2>
        <p className="text-lg text-gray-600 max-w-3xl mx-auto">
          基于真实案例数据，计算采用CActor框架为您的业务带来的投资回报。
        </p>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
        {/* 输入参数 */}
        <div className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center">
                <Target className="w-5 h-5 mr-2" />
                业务参数设置
              </CardTitle>
              <CardDescription>
                请输入您当前的业务指标，我们将基于行业基准数据计算ROI。
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
              {/* 行业选择 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-3">
                  选择行业类型
                </label>
                <div className="grid grid-cols-2 gap-3">
                  {Object.entries(industryBenchmarks).map(
                    ([key, benchmark]) => (
                      <Button
                        key={key}
                        variant={
                          selectedIndustry === key ? 'default' : 'outline'
                        }
                        onClick={() =>
                          setSelectedIndustry(
                            key as keyof typeof industryBenchmarks
                          )
                        }
                        className="h-auto p-4 flex flex-col items-center"
                      >
                        <div className="text-2xl mb-2">{benchmark.icon}</div>
                        <div className="text-sm font-medium">
                          {benchmark.name}
                        </div>
                      </Button>
                    )
                  )}
                </div>
              </div>

              <Separator />

              {/* 业务指标输入 */}
              <div className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    日交易量
                  </label>
                  <Input
                    type="number"
                    value={inputs.currentTransactions}
                    onChange={e =>
                      updateInput(
                        'currentTransactions',
                        parseInt(e.target.value) || 0
                      )
                    }
                    placeholder="1000000"
                  />
                  <p className="text-xs text-gray-500 mt-1">
                    当前系统每日处理的交易数量
                  </p>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    平均延迟 (毫秒)
                  </label>
                  <Input
                    type="number"
                    value={inputs.currentLatency}
                    onChange={e =>
                      updateInput(
                        'currentLatency',
                        parseInt(e.target.value) || 0
                      )
                    }
                    placeholder="100"
                  />
                  <p className="text-xs text-gray-500 mt-1">
                    当前系统的平均响应延迟
                  </p>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    年度运营成本 (元)
                  </label>
                  <Input
                    type="number"
                    value={inputs.currentCost}
                    onChange={e =>
                      updateInput('currentCost', parseInt(e.target.value) || 0)
                    }
                    placeholder="1000000"
                  />
                  <p className="text-xs text-gray-500 mt-1">
                    包括基础设施、人力等总成本
                  </p>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    开发团队规模
                  </label>
                  <Input
                    type="number"
                    value={inputs.teamSize}
                    onChange={e =>
                      updateInput('teamSize', parseInt(e.target.value) || 0)
                    }
                    placeholder="5"
                  />
                  <p className="text-xs text-gray-500 mt-1">
                    参与项目的开发人员数量
                  </p>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    项目周期 (月)
                  </label>
                  <Input
                    type="number"
                    value={inputs.projectDuration}
                    onChange={e =>
                      updateInput(
                        'projectDuration',
                        parseInt(e.target.value) || 0
                      )
                    }
                    placeholder="6"
                  />
                  <p className="text-xs text-gray-500 mt-1">
                    预计的项目实施周期
                  </p>
                </div>
              </div>

              <Button
                onClick={calculateROI}
                className="w-full bg-blue-600 hover:bg-blue-700"
              >
                <Calculator className="w-4 h-4 mr-2" />
                计算投资回报
                <ArrowRight className="w-4 h-4 ml-2" />
              </Button>
            </CardContent>
          </Card>
        </div>

        {/* 计算结果 */}
        <div className="space-y-6">
          {results ? (
            <>
              {/* 核心指标 */}
              <Card className="bg-gradient-to-br from-blue-50 to-cyan-50">
                <CardHeader>
                  <CardTitle className="flex items-center">
                    <TrendingUp className="w-5 h-5 mr-2 text-blue-600" />
                    投资回报分析
                  </CardTitle>
                  <CardDescription>
                    基于 {industryBenchmarks[selectedIndustry].name}{' '}
                    行业基准数据计算
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="grid grid-cols-2 gap-4">
                    <div className="text-center p-4 bg-white rounded-lg shadow-sm">
                      <div className="text-3xl font-bold text-green-600 mb-2">
                        {formatPercentage(results.totalROI)}
                      </div>
                      <div className="text-sm text-gray-600">3年总ROI</div>
                    </div>
                    <div className="text-center p-4 bg-white rounded-lg shadow-sm">
                      <div className="text-3xl font-bold text-blue-600 mb-2">
                        {results.paybackPeriod.toFixed(1)}月
                      </div>
                      <div className="text-sm text-gray-600">投资回收期</div>
                    </div>
                  </div>
                </CardContent>
              </Card>

              {/* 详细收益分析 */}
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center">
                    <BarChart3 className="w-5 h-5 mr-2" />
                    收益明细分析
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="flex items-center justify-between p-4 bg-green-50 rounded-lg">
                    <div className="flex items-center">
                      <TrendingUp className="w-5 h-5 text-green-600 mr-3" />
                      <div>
                        <div className="font-semibold text-gray-900">
                          性能提升收益
                        </div>
                        <div className="text-sm text-gray-600">
                          提升{results.performanceImprovement}%处理能力
                        </div>
                      </div>
                    </div>
                    <div className="text-lg font-bold text-green-600">
                      {formatCurrency(results.revenueIncrease)}/年
                    </div>
                  </div>

                  <div className="flex items-center justify-between p-4 bg-blue-50 rounded-lg">
                    <div className="flex items-center">
                      <DollarSign className="w-5 h-5 text-blue-600 mr-3" />
                      <div>
                        <div className="font-semibold text-gray-900">
                          运营成本节约
                        </div>
                        <div className="text-sm text-gray-600">
                          降低
                          {industryBenchmarks[selectedIndustry].costReduction}
                          %运营成本
                        </div>
                      </div>
                    </div>
                    <div className="text-lg font-bold text-blue-600">
                      {formatCurrency(results.costSavings)}/年
                    </div>
                  </div>

                  <div className="flex items-center justify-between p-4 bg-orange-50 rounded-lg">
                    <div className="flex items-center">
                      <Clock className="w-5 h-5 text-orange-600 mr-3" />
                      <div>
                        <div className="font-semibold text-gray-900">
                          延迟优化收益
                        </div>
                        <div className="text-sm text-gray-600">
                          降低
                          {
                            industryBenchmarks[selectedIndustry]
                              .latencyReduction
                          }
                          %响应延迟
                        </div>
                      </div>
                    </div>
                    <div className="text-lg font-bold text-orange-600">
                      质量提升
                    </div>
                  </div>

                  <Separator />

                  <div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
                    <div className="flex items-center">
                      <Target className="w-5 h-5 text-gray-600 mr-3" />
                      <div>
                        <div className="font-semibold text-gray-900">
                          实施成本
                        </div>
                        <div className="text-sm text-gray-600">
                          一次性投资成本
                        </div>
                      </div>
                    </div>
                    <div className="text-lg font-bold text-gray-600">
                      {formatCurrency(results.implementationCost)}
                    </div>
                  </div>
                </CardContent>
              </Card>

              {/* 行业对比 */}
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center">
                    <PieChart className="w-5 h-5 mr-2" />
                    行业基准对比
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="space-y-3">
                    {Object.entries(industryBenchmarks).map(
                      ([key, benchmark]) => (
                        <div
                          key={key}
                          className={`p-3 rounded-lg border ${
                            selectedIndustry === key
                              ? 'border-blue-200 bg-blue-50'
                              : 'border-gray-200'
                          }`}
                        >
                          <div className="flex items-center justify-between">
                            <div className="flex items-center">
                              <div className="text-lg mr-3">
                                {benchmark.icon}
                              </div>
                              <div>
                                <div className="font-medium text-gray-900">
                                  {benchmark.name}
                                </div>
                                <div className="text-sm text-gray-600">
                                  性能+{benchmark.performanceGain}% · 延迟-
                                  {benchmark.latencyReduction}% · 成本-
                                  {benchmark.costReduction}%
                                </div>
                              </div>
                            </div>
                            {selectedIndustry === key && (
                              <Badge className="bg-blue-100 text-blue-700">
                                当前选择
                              </Badge>
                            )}
                          </div>
                        </div>
                      )
                    )}
                  </div>
                </CardContent>
              </Card>
            </>
          ) : (
            <Card className="h-full flex items-center justify-center">
              <CardContent className="text-center py-12">
                <Calculator className="w-16 h-16 text-gray-300 mx-auto mb-4" />
                <h3 className="text-lg font-semibold text-gray-900 mb-2">
                  准备计算投资回报
                </h3>
                <p className="text-gray-600 mb-6">
                  请在左侧输入您的业务参数，点击计算按钮获取详细的ROI分析报告。
                </p>
                <div className="space-y-2 text-sm text-gray-500">
                  <div className="flex items-center justify-center">
                    <Zap className="w-4 h-4 mr-2" />
                    基于真实案例数据
                  </div>
                  <div className="flex items-center justify-center">
                    <Users className="w-4 h-4 mr-2" />
                    行业基准对比分析
                  </div>
                  <div className="flex items-center justify-center">
                    <TrendingUp className="w-4 h-4 mr-2" />
                    3年期投资回报预测
                  </div>
                </div>
              </CardContent>
            </Card>
          )}
        </div>
      </div>
    </div>
  );
}

export default ROICalculator;
